

/*
逻辑控制，增删改查
*/ 
const mongoose=require('mongoose');
const Cate=require('../models/newscate.model');
/*增 */
exports.create=function(req,res,next){
        const cate=new Cate(req.body);
        cate.save()
        .then(data=>{
            res.json(data)
        })
}
/*修*/
exports.update=function(req,res,next){
    const id=req.params.id;
    const cate=new  Cate(req.body);
    Cate.findByIdAndUpdate(id,{$set:req.body},{new:false})
    .then(data=>{
        res.json(data);
    })
}

function reverseTree(data,pid){
    var result=[],
    temp;
    var data=JSON.parse(JSON.stringify(data));
    for (const i in data) {
        if (data[i].parentId===pid) {
          result.push(data[i]);
          temp=reverseTree(data,data[i]._id);
          if(temp.length>0){
              data[i].children=temp;
          }
            
        }
    }
    return result;

}
/*查 */
exports.list=function(req,res,next){
    console.log(req);
    var type=req.params.type || 0;
    Cate.find({type:type},function(err,data){
        var rpTree=reverseTree(data,null);
        res.json(rpTree);
    })
}


/*删除 */
exports.remove=function(req,res,next){
    var id=req.params.id;
    var ids=[];

    Cate.findOne({_id:id},function(err,doc){
        console.log(doc);
        if(doc){
            ids=[doc.id]
            doc.getChildren().then(function(docs){
               for(let i=0;i<docs.length;i++){
                   ids.push(docs[i]._id)
               }
             Cate.remove({_id:{$in:ids}})
             .then(data=>{
                 res.json({'message':'数据删除成功'})
             })
            })
        }
    })


}